package controller

import (
	"fmt"
	"log"
	"net/http"

	"gitee.com/wangshh_123/cross-pay-go/src/controller/platform"
	"gitee.com/wangshh_123/cross-pay-go/src/database"
	platformCommon "gitee.com/wangshh_123/cross-pay-go/src/platform/common"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/hlPay"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	photonmodels "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/models"
	photonpayServices "gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay/services"
	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"

	"github.com/gin-gonic/gin"
)

// --- 自定义 ResponseWriter 用于捕获输出 ---
type bodyWriter struct {
	gin.ResponseWriter
	body []byte
}

func (w *bodyWriter) Write(b []byte) (int, error) {
	w.body = append(w.body, b...)
	return w.ResponseWriter.Write(b)
}

// UserInfoController 用户信息控制器
type UserInfoController struct {
	cardListController *platform.CardListController
}

// NewUserInfoController 创建用户信息控制器
func NewUserInfoController(cardListController *platform.CardListController) *UserInfoController {
	return &UserInfoController{
		cardListController: cardListController,
	}
}

// GetCurrentUserInfo 获取当前用户信息
func (c *UserInfoController) GetCurrentUserInfo(ctx *gin.Context) {
	// 从JWT token中获取当前用户信息
	userID, err := common.GetCurrentUserID(ctx)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "user_id_not_found", err)
		return
	}

	username, err := common.GetCurrentUsername(ctx)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "username_not_found", err)
		return
	}

	roleID, err := common.GetCurrentRoleID(ctx)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "role_id_not_found", err)
		return
	}

	// 构建用户信息响应
	userInfo := gin.H{
		"user_id":  userID,
		"username": username,
		"role_id":  roleID,
	}

	common.Success(ctx, "获取用户信息成功", userInfo)
}

// GetCurrentUserID 获取当前用户ID
func (c *UserInfoController) GetCurrentUserID(ctx *gin.Context) {
	userID, ok := common.RequireCurrentUserID(ctx)
	if !ok {
		return // 错误响应已在RequireCurrentUserID中处理
	}

	common.Success(ctx, "获取用户ID成功", gin.H{
		"user_id": userID,
	})
}

// GetHomeInfo 获取首页信息（只返回卡统计信息）
func (c *UserInfoController) GetHomeInfo(ctx *gin.Context) {
	platform, statistics, err := c.cardListController.GetCardStatistics(ctx)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_card_statistics_failed", err)
		return
	}

	// 获取当前用户ID
	userID, err := common.GetCurrentUserID(ctx)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "user_id_not_found", err)
		return
	}

	// 获取当前用户角色
	roleID, err := common.GetCurrentRoleID(ctx)
	if err != nil {
		common.Error(ctx, http.StatusUnauthorized, "role_id_not_found", err)
		return
	}

	// 获取matrixAccount
	var matrixAccount string
	var userMatrixAccount struct {
		MatrixAccount string `gorm:"column:matrix_account"`
		PlatformType  string `gorm:"column:platform_type"`
	}
	db := database.DB // 直接用全局DB
	db.Table("user_matrix_accounts").Select("matrix_account, platform_type").Where("user_id = ? AND status = 'active'", userID).First(&userMatrixAccount)
	matrixAccount = userMatrixAccount.MatrixAccount

	// 查询管理员转账记录
	var totalIn, totalOut float64
	db.Table("admin_transfer_records").
		Where("platform_account = ? AND status = ?", matrixAccount, "success").
		Select("SUM(CASE WHEN transfer_type = 'transfer_in' THEN transfer_amount ELSE 0 END) as total_in, SUM(CASE WHEN transfer_type = 'transfer_out' THEN transfer_amount ELSE 0 END) as total_out").
		Row().Scan(&totalIn, &totalOut)
	adminTotalTransfer := totalIn - totalOut

	// 统计主账号划转金额
	var masterTransferAmount float64 = 0
	if roleID == 3 {
		var allocateSum, refundSum float64
		// 先查主账号ID
		var masterAccount struct{ ID int64 }
		db.Table("master_accounts").Select("id").Where("user_id = ?", userID).First(&masterAccount)
		db.Table("master_sub_account_funds").
			Where("master_account_id = ?", masterAccount.ID).
			Select("SUM(CASE WHEN type = 'allocate' THEN amount ELSE 0 END) as allocate_sum, SUM(CASE WHEN type = 'refund' THEN amount ELSE 0 END) as refund_sum").
			Row().Scan(&allocateSum, &refundSum)
		masterTransferAmount = allocateSum - refundSum
	}

	// 获取交易笔数
	var transactionCount int64 = 0
	if userMatrixAccount.PlatformType == "photonpay" {
		// 调用photonpay的交易统计
		transactionCount, err = c.getPhotonPayTransactionCount(ctx, matrixAccount)
		if err != nil {
			log.Printf("获取photonpay交易笔数失败: %v", err)
			// 不中断流程，继续返回其他数据
		}
	} else if userMatrixAccount.PlatformType == "hlpay" {
		// 调用hlpay的交易统计
		transactionCount, err = c.getHlPayTransactionCount(ctx, userID)
		if err != nil {
			log.Printf("获取hlpay交易笔数失败: %v", err)
			// 不中断流程，继续返回其他数据
		}
	}

	common.Success(ctx, gin.H{
		"platform":               platform,
		"statistics":             statistics,
		"admin_total_transfer":   adminTotalTransfer,
		"master_transfer_amount": masterTransferAmount,
		"transaction_count":      transactionCount,
	})
}

// getPhotonPayTransactionCount 获取photonpay平台交易笔数
func (c *UserInfoController) getPhotonPayTransactionCount(ctx *gin.Context, matrixAccount string) (int64, error) {
	// 构建查询参数，只获取第一页数据
	params := photonmodels.VccTradeOrderQueryParams{
		PageIndex:     1,
		PageSize:      1, // 只需要1条数据来获取total
		MatrixAccount: matrixAccount,
	}

	// 调用photonpay的service层方法
	// 需要导入photonpay的service和models
	photonpayConfig := &platformCommon.PlatformConfig{
		AppID:      "default",
		AppSecret:  "default",
		GatewayURL: "default",
		Timeout:    30,
	}
	photonpayClient := photonpay.GetPhotonPayClient(photonpayConfig)
	result, err := photonpayServices.GetVccTradeOrderList(ctx, photonpayClient, params)
	if err != nil {
		return 0, err
	}

	return result.Total, nil
}

// getHlPayTransactionCount 获取hlpay平台交易笔数
func (c *UserInfoController) getHlPayTransactionCount(ctx *gin.Context, userID int64) (int64, error) {
	// 调用hlpay的service层方法
	// 需要创建HlPayTransactionCacheService实例
	hlpayConfig := &hlPay.HlPayConfig{
		ClientID:       "default",
		ClientKey:      "default",
		ClientSecret:   "default",
		GatewayURL:     "default",
		RefreshTime:    30,
		MinRefreshTime: 10,
	}
	hlpayClient := hlPay.GetHlPayClient(hlpayConfig)
	cacheService := service.NewHlPayTransactionCacheService(hlpayClient, nil)

	// 直接从Redis获取用户交易总数，不通过分页
	userTxListKey := fmt.Sprintf("hlpay_user_transactions:%d", userID)
	total, err := database.RedisClient.ZCard(ctx, userTxListKey).Result()
	if err != nil {
		log.Printf("HlPay获取用户交易总数失败: %v", err)
		return 0, err
	}

	// 如果缓存中没有数据，尝试同步
	if total == 0 {
		log.Printf("HlPay缓存中没有交易数据，尝试同步...")

		// 触发同步
		syncResult, err := cacheService.SyncRecentTransactions(ctx)
		if err != nil {
			log.Printf("HlPay同步交易数据失败: %v", err)
			return 0, err
		}

		log.Printf("HlPay同步完成，新增记录: %d", syncResult.NewRecords)

		// 同步后重新获取总数
		total, err = database.RedisClient.ZCard(ctx, userTxListKey).Result()
		if err != nil {
			log.Printf("HlPay同步后获取总数失败: %v", err)
			return 0, err
		}
	}

	return total, nil
}
